package com.vivz.baby.domain;

import java.util.Calendar;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.time.DateUtils;

import com.vivz.baby.enumeration.LogEntryType;

@Entity
@Table(name = "LOG")
public class Log extends AbstractEntity {
	
	private static final long serialVersionUID = 1L;
	
	@ManyToOne(fetch = FetchType.EAGER, optional = false)
	@JoinColumn(name = "USER_ID", nullable = false, updatable = false)
	private User user;
	
	@Column(name = "ENTRY_TYPE_ID")
	private Long entryTypeId;
	
	@Column(name = "ENTRY_VALUE")
	private String value;
	
	@Column(name = "LOG_TIME", nullable = false)
	private Date logTime;
	
	public User getUser() {
		return user;
	}
	
	public void setUser(final User user) {
		this.user = user;
	}
	
	public LogEntryType getLogEntryType() {
		return LogEntryType.getInstance(entryTypeId.intValue());
	}
	
	public void setLogEntryType(final LogEntryType logEntryType) {
		entryTypeId = Long.valueOf(logEntryType.getId());
	}
	
	public String getValue() {
		return value;
	}
	
	public void setValue(final String value) {
		this.value = value;
	}
	
	public Date getLogTime() {
		return logTime;
	}
	
	public void setLogTime(final Date logTime) {
		this.logTime = roundDate(logTime);
	}
	
	private Date roundDate(final Date timestamp) {
		final Date round;
		if (timestamp == null) {
			round = null;
		} else {
			round = DateUtils.round(timestamp, Calendar.MINUTE);
		}
		return round;
	}
	
	@Override
	public String toString() {
		return new ToStringBuilder(this) //
				.append(getId()) //
				.append(user) //
				.append(getLogEntryType()) //
				.append(value) //
				.append(logTime) //
				.toString();
	}
	
}
